import {getItem, removeItem, setItem} from "../services/LocalDataService";
import update from "react-addons-update";
import {getLanguageByKey} from "../../i18n/i18n";

const titleName: string = "titleMap";

const webTitle: any = getLanguageByKey("webTitle");

const TitleReducer: object = {
    namespace: "titleReducer",
    state: {
        titleMap: {
            "/home": {
                titleCn: webTitle.zh,
                titleEn: webTitle.en
            }
        }
    },
    initTitleMap: function () {
        let newTitleMap = getItem(titleName) || this.state.titleMap;
        return update(this.state, {titleMap: {$set: newTitleMap}});
    },
    addTitleMap: function (params: any) {
        const {key, value}: { key: string, value: string } = params,
            {titleMap}: { titleMap: any } = this.state;

        titleMap[key] = value;

        setItem(titleName, titleMap);

        return update(this.state, {titleMap: {$set: titleMap}});
    },

    removeTitleMap: function (params: any) {
        const {key}: { key: string } = params,
            {titleMap}: { titleMap: any } = this.state;

        if (titleMap[key]) {
            delete titleMap[key]
        }

        setItem(titleName, titleMap);

        return update(this.state, {titleMap: {$set: titleMap}});
    },
    removeAll: function () {
        removeItem(titleName);
        return update(this.state, {titleMap: {$set: {}}});
    }
}

export default TitleReducer;